library(data.table)
library(Hmisc)
library(lfe)
library(stargazer)


setwd("/zfs/projects/faculty/buchak-beyond-balance-sheet/reduced_form/code/")

tableSix <- function() {
  
  hmda.in <- fread('../data/loans07to17.csv')
  #limits <- readstata13::read.dta13('../data/conforming_post2007.dta')
  
  hmda.in[,state_county := paste(state_code,county_code)]
  
  # by market
  byMarket <- hmda.in[,j=list(.N, bank.share = mean(1-sb,na.rm=T),jumbo.share = mean(loan_amount > conforming_limit,na.rm=T),
                              bunch.share = mean(loan_amount / conforming_limit > .95 & loan_amount / conforming_limit < 1.05,na.rm=T),
                              c.lim = conforming_limit[1]),by=c('year','state_county')]
  
  market.2007 <- byMarket[year == 2007,c('state_county','c.lim')]
  merged <- merge(byMarket,market.2007,by='state_county',suffixes = c('','.base'))  
  
  
  # Run regression
  qq1 <- felm(jumbo.share ~ I(c.lim / c.lim.base) | year + state_county,data = merged,weights=merged$N)
  qq2 <- felm(bunch.share ~ I(c.lim / c.lim.base) | year + state_county,data = merged,weights=merged$N)
  qq3 <- felm(bank.share ~ I(c.lim / c.lim.base) | year + state_county,data = merged,weights=merged$N)
  qq4 <- felm(bank.share ~ jumbo.share | year + state_county,data = merged,weights=merged$N)
  
  stargazer(qq1,qq2,qq3,qq4,type = 'html')
  
}